<template>
<div class="login-container">
  <div class="login-form-wrap">
    <div class="login-head">
      <div class="logo"></div>
    </div>
    <!-- 表单 -->
    <el-form :model="form" status-icon :rules="rules" ref="form" class="login-form">
      <el-form-item prop="mobile">
        <el-input placeholder="请输入手机号码" v-model="form.mobile"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input placeholder="请输入验证码" v-model="form.code"></el-input>
      </el-form-item>
      <el-form-item prop="isAgree">
        <el-checkbox v-model="form.isAgree">我已阅读用户协议和隐私条款</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-btn" @click.native='myLogin'>登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>
<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  data () {
    return {
      form: {
        mobile: '13911111111',
        code: '246810',
        isAgree: true
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
          { pattern: /^\d{11}$/, message: '长度必须是11位的纯数字', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
          { pattern: /^\d{6}$/, message: '长度是6个字符', trigger: ['blur', 'change'] }
        ],
        isAgree: [
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('请阅读隐私协议'))
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    myLogin () {
      this.$refs.form.validate((valid) => { // form即文档中所传的参数ref的内容
        if (valid) {
          // 点击登录发送axios请求，存token，进入登录的首页
          login(this.form.mobile, this.form.code).then(res => {
            // console.log('发送请求成功设置token', res.data.token)
            setToken(res.data.token)
            this.$router.push('/')
          })
          this.$message({
            message: '恭喜你，登录成功',
            type: 'success' // 为提示消息的颜色
          })
        } else {
          this.$message({
            message: '登陆失败，稍后请重新登录',
            type: 'false' // 为提示消息的颜色
          })
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
// 铺满整屏
.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("~@/assets/login_bg.jpg") no-repeat;
  background-size: cover;
  .login-form-wrap {
    width: 400px;
    padding: 30px 50px 10px;
    background-color: #fff;
    .login-head {
      display: flex;
      justify-content: center;
      .logo {
        width: 200px;
        height: 57px;
        background: url("~@/assets/logo_index.png") no-repeat;
        background-size: contain;
      }
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>
